/**
 * 
 */
package pTime;

import java.util.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;


/**
 * @author JC PIERSON
 *
 */
public class TaskFrame extends JFrame implements ListSelectionListener {
	
	private TaskTableModel model = null;
    
    private Properties startSettings = null;
    
    private javax.swing.JButton addButton;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JButton removeButton;
    private javax.swing.JButton resetButton;
    private javax.swing.JButton startButton;
    private javax.swing.JButton stopButton;
    
    /**
     * Time consumption column width
     */
    public static final int CONS_COL_WIDTH = 80;
    
    /**
     * Creates new form TaskFrame
     */
    public TaskFrame() {
        model = new TaskTableModel(this);
        initComponents();
        TableColumn tct = jTable1.getColumnModel().getColumn(1);
        tct.setMaxWidth(CONS_COL_WIDTH);
        tct.setPreferredWidth(CONS_COL_WIDTH);
        TableColumn tcp = jTable1.getColumnModel().getColumn(2);
        tcp.setMaxWidth(CONS_COL_WIDTH/2);
        tcp.setPreferredWidth(CONS_COL_WIDTH/2);
        
        jTable1.getSelectionModel().addListSelectionListener(this);
        updateButtons();
        
        try {
            String xs = startSettings.getProperty("window.location.x");
            String ys = startSettings.getProperty("window.location.y");
            if (xs != null && ys != null) {
                setLocation(Integer.parseInt(xs), Integer.parseInt(ys));
            }
        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(null, "Cannot load window location (bad format).", "Error", JOptionPane.ERROR_MESSAGE);
        }
        
        try {
            String ws = startSettings.getProperty("window.size.w");
            String hs = startSettings.getProperty("window.size.h");
            if (ws != null && hs != null) {
                setSize(Integer.parseInt(ws), Integer.parseInt(hs));
            }
        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(null, "Cannot load window size (bad format).", "Error", JOptionPane.ERROR_MESSAGE);
        }
    }
    
    
    /**
     * Sets initial (start) settings.
     * @param props properties with initial settings
     */
    public void setStartSettings(Properties props) {
        startSettings = props;
    }
    
    /**
     * Updates the buttons' state.
     */
    private void updateButtons() {
        int cnt = jTable1.getSelectedRowCount();
        if (cnt == 0) {
            startButton.setEnabled(false);
            stopButton.setEnabled(false);
            removeButton.setEnabled(false);
            resetButton.setEnabled(false);
        }
        else {
            int start = jTable1.getSelectedRow();
            int end = start + cnt - 1;
            removeButton.setEnabled(true);
            resetButton.setEnabled(true);
            
            int rcnt = 0;
            for (int i=start; i<=end; i++) {
                if (model.isRunning(i))
                    rcnt++;
            }
            startButton.setEnabled(rcnt < cnt);
            stopButton.setEnabled(rcnt > 0);
        }
    }
    
    /**
     * Updates the buttons according the current selection.
     * @param e list selection event
     */
    public void valueChanged(ListSelectionEvent e) {
        updateButtons();
    }
    
    private void initComponents() {

        jSplitPane1 = new javax.swing.JSplitPane();
        jPanel1 = new javax.swing.JPanel();
        startButton = new javax.swing.JButton();
        stopButton = new javax.swing.JButton();
        addButton = new javax.swing.JButton();
        removeButton = new javax.swing.JButton();
        resetButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("TimeAllocator");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                TaskFrame.this.windowClosing(evt);
            }
        });

        jSplitPane1.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);

        jPanel1.setMinimumSize(new java.awt.Dimension(10, 25));

        startButton.setText("Start");
        startButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                startPressed(evt);
            }
        });

        stopButton.setText("Stop");
        stopButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                stopPressed(evt);
            }
        });

        addButton.setText("Add");
        addButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addPressed(evt);
            }
        });

        removeButton.setText("Remove");
        removeButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                removePressed(evt);
            }
        });

        resetButton.setText("Reset");
        resetButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                resetPressed(evt);
            }
        });

        GroupLayout jPanel1Layout = new GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .add(startButton)
                .addPreferredGap(LayoutStyle.RELATED)
                .add(stopButton)
                .addPreferredGap(LayoutStyle.RELATED)
                .add(addButton)
                .addPreferredGap(LayoutStyle.RELATED)
                .add(removeButton)
                .addPreferredGap(LayoutStyle.RELATED)
                .add(resetButton)
                .addPreferredGap(LayoutStyle.RELATED)
                .addContainerGap(152, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(GroupLayout.BASELINE)
            .add(startButton, GroupLayout.DEFAULT_SIZE, 25, Short.MAX_VALUE)
            .add(stopButton, GroupLayout.DEFAULT_SIZE, 25, Short.MAX_VALUE)
            .add(addButton, GroupLayout.DEFAULT_SIZE, 25, Short.MAX_VALUE)
            .add(removeButton, GroupLayout.DEFAULT_SIZE, 25, Short.MAX_VALUE)
            .add(resetButton, GroupLayout.DEFAULT_SIZE, 25, Short.MAX_VALUE)
        );

        jSplitPane1.setTopComponent(jPanel1);

        /* jScrollPane1.setPreferredSize(new java.awt.Dimension(454, 400)); */
        jScrollPane1.setVerifyInputWhenFocusTarget(false);

        jTable1.setModel(model);
        jTable1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_INTERVAL_SELECTION);
        jTable1.setDefaultRenderer(StringBuffer.class, new DefaultTableCellRenderer() {
            private Color fg = Color.RED;
            private Color bg = new Color(255, 240, 240);

            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
                Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);

                if (JLabel.class.isAssignableFrom(c.getClass())) {
                    ((JLabel) c).setHorizontalAlignment(JLabel.TRAILING);
                }

                if (model.isRunning(row)) {
                    c.setForeground(fg);
                    if (!isSelected)
                    c.setBackground(bg);
                }
                else {
                    c.setForeground(Color.BLACK);
                    if (!isSelected)
                    c.setBackground(Color.WHITE);
                }

                return c;
            }
        });
        jScrollPane1.setViewportView(jTable1);

        jSplitPane1.setRightComponent(jScrollPane1);

        GroupLayout layout = new GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(GroupLayout.LEADING)
            .add(GroupLayout.TRAILING, jSplitPane1, GroupLayout.DEFAULT_SIZE, 360, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(GroupLayout.LEADING)
            .add(jSplitPane1, GroupLayout.DEFAULT_SIZE, 160, Short.MAX_VALUE)
        );

        pack();
    }

    private void resetPressed(java.awt.event.ActionEvent evt) {
        int start = jTable1.getSelectedRow();
        int cnt = jTable1.getSelectedRowCount();
        if (cnt > 0)
            model.resetTasks(start, start + cnt - 1);
    }

    private void windowClosing(java.awt.event.WindowEvent evt) {
        model.stopAllTasks();
        model.saveToFile();
    }

    private void removePressed(java.awt.event.ActionEvent evt) {
        int start = jTable1.getSelectedRow();
        int cnt = jTable1.getSelectedRowCount();
        if (cnt > 0)
            model.removeTasks(start, start + cnt - 1);
            
    }

    private void addPressed(java.awt.event.ActionEvent evt) {
        model.addNewTask();
    }
    private void stopPressed(java.awt.event.ActionEvent evt) {
        int start = jTable1.getSelectedRow();
        int cnt = jTable1.getSelectedRowCount();
        if (cnt > 0) {
            model.stopTasks(start, start + cnt - 1);
            updateButtons();
        }
    }

    private void startPressed(java.awt.event.ActionEvent evt) {
        int start = jTable1.getSelectedRow();
        int cnt = jTable1.getSelectedRowCount();
        if (cnt > 0) {
            model.startTasks(start, start + cnt - 1);
            updateButtons();
        }
    }

}
